import { useState, useEffect, useCallback } from 'react'

// 简单的内存缓存
const cache = new Map()

// 缓存配置
const CACHE_CONFIG = {
  // 缓存过期时间（毫秒）
  TTL: 5 * 60 * 1000, // 5分钟
  // 最大缓存条目数
  MAX_ENTRIES: 50
}

// 缓存条目结构
class CacheEntry {
  constructor(data, ttl = CACHE_CONFIG.TTL) {
    this.data = data
    this.timestamp = Date.now()
    this.ttl = ttl
  }

  isValid() {
    return Date.now() - this.timestamp < this.ttl
  }
}

// 清理过期缓存
const cleanupCache = () => {
  const now = Date.now()
  for (const [key, entry] of cache.entries()) {
    if (!entry.isValid()) {
      cache.delete(key)
    }
  }
  
  // 如果缓存条目过多，删除最旧的
  if (cache.size > CACHE_CONFIG.MAX_ENTRIES) {
    const entries = Array.from(cache.entries())
    entries.sort((a, b) => a[1].timestamp - b[1].timestamp)
    
    const toDelete = entries.slice(0, cache.size - CACHE_CONFIG.MAX_ENTRIES)
    toDelete.forEach(([key]) => cache.delete(key))
  }
}

// 数据缓存Hook
export const useCache = (key, fetcher, options = {}) => {
  const {
    ttl = CACHE_CONFIG.TTL,
    enabled = true,
    dependencies = []
  } = options

  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)

  const fetchData = useCallback(async (forceRefresh = false) => {
    if (!enabled) return

    // 检查缓存
    if (!forceRefresh && cache.has(key)) {
      const entry = cache.get(key)
      if (entry.isValid()) {
        setData(entry.data)
        return
      } else {
        cache.delete(key)
      }
    }

    try {
      setLoading(true)
      setError(null)
      
      const result = await fetcher()
      
      // 缓存数据
      cache.set(key, new CacheEntry(result, ttl))
      setData(result)
      
      // 清理过期缓存
      cleanupCache()
    } catch (err) {
      setError(err)
      console.error('Cache fetch error:', err)
    } finally {
      setLoading(false)
    }
  }, [key, fetcher, ttl, enabled, ...dependencies])

  // 清除缓存
  const clearCache = useCallback(() => {
    cache.delete(key)
    setData(null)
  }, [key])

  // 清除所有缓存
  const clearAllCache = useCallback(() => {
    cache.clear()
    setData(null)
  }, [])

  // 刷新数据
  const refresh = useCallback(() => {
    return fetchData(true)
  }, [fetchData])

  useEffect(() => {
    fetchData()
  }, [fetchData])

  return {
    data,
    loading,
    error,
    refresh,
    clearCache,
    clearAllCache
  }
}

// 预加载数据
export const usePreload = (key, fetcher) => {
  const preload = useCallback(async () => {
    if (!cache.has(key)) {
      try {
        const result = await fetcher()
        cache.set(key, new CacheEntry(result))
      } catch (error) {
        console.error('Preload error:', error)
      }
    }
  }, [key, fetcher])

  return preload
}

// 缓存统计
export const getCacheStats = () => {
  cleanupCache()
  return {
    size: cache.size,
    keys: Array.from(cache.keys()),
    maxEntries: CACHE_CONFIG.MAX_ENTRIES,
    ttl: CACHE_CONFIG.TTL
  }
}

export default useCache
